package com.luyang.framework.validator;

import com.luyang.framework.validator.annotation.CheckPhoneNum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 校验手机号是否合法
 *
 * @author lu_yang
 */
public class PhoneNumValidator implements ConstraintValidator<CheckPhoneNum, String> {

    private static final String PHONE_NUMBER_RULE = "(?:0|86|\\+86)?1[3-9]\\d{9}";

    private Boolean required;

    @Override
    public void initialize(CheckPhoneNum constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String phoneNum, ConstraintValidatorContext constraintValidatorContext) {
        if (null == phoneNum || phoneNum.trim().length() == 0) {
            return !required;
        }

        return Pattern.matches(PHONE_NUMBER_RULE, phoneNum);
    }
}
